package com.anjiplus.template.gaea.auth.config;

import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.utils.ApplicationContextUtils;
import com.anji.plus.gaea.utils.JwtBean;
import com.anjiplus.template.gaea.auth.modules.websocket.MyPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * 功能描述：
 * websocket用户相关渠道拦截
 * @Author: peiyanni
 * @Date: 2021/4/2 14:30
 */
@Slf4j
public class UserChannelInterceptor implements ChannelInterceptor {
    @Autowired(required = false)
    private SimpUserRegistry simpUserRegistry;

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())){
            String username=null;
            try {
                String token = accessor.getNativeHeader(GaeaConstant.Authorization).get(0);
                //校验token
                JwtBean jwtBean = ApplicationContextUtils.getBean(JwtBean.class);
                username = jwtBean.getUsername(token);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("token is error");
                throw new IllegalStateException("The token is illegal");
            }
            if(StringUtils.isEmpty(username)){
                log.error("token is overtime");
                throw new IllegalStateException("The token is illegal");
            }
            accessor.setUser(new MyPrincipal(username));
            log.info("【{}】用户上线了,当前在线人数--{}",username,simpUserRegistry.getUserCount());
        }else if(StompCommand.DISCONNECT.equals(accessor.getCommand())){
            log.info("【{}】用户下线了,当前在线人数--{}",accessor.getUser().getName(),simpUserRegistry.getUserCount());
        }
        return message;
    }


}
